/*
 * FinancialCalendarApp.java
 */

package financialcalendar;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.regex.Pattern;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;

/**
 * The main class of the application.
 * This creates the view.
 */
public class FinancialCalendarApp extends SingleFrameApplication {
    public static User currentUser;
    static Scanner fileScanner;
    static PrintWriter fileWriter;
    /**
     * At startup create and show the main frame of the application.
     */
    @Override protected void startup() {
        show(new FinancialCalendarView(this));
    }

    /**
     * This method is to initialize the specified window by injecting resources.
     * Windows shown in our application come fully initialized from the GUI
     * builder, so this additional configuration is not needed.
     */
    @Override protected void configureWindow(java.awt.Window root) {
    }

    /**
     * A convenient static getter for the application instance.
     * @return the instance of FinancialCalendarApp
     */
    public static FinancialCalendarApp getApplication() {
        return Application.getInstance(FinancialCalendarApp.class);
    }

    /**
     * Main method launching the application.
     */
    public static void main(String[] args) {
        initializeStuff();
        if (FinancialCalendar.monthChange(currentUser.prevMonth))
        {
            currentUser.amountSaved2MonthsAgo = currentUser.amountSavedLastMonth;
            currentUser.amountSaved2MonthsAgo = currentUser.amountSavedLastMonth;
            currentUser.amountSaved2MonthsAgo = currentUser.amountSavedLastMonth;
        }
        currentUser.myCalendar.calculateIdealProjectedSavings(currentUser);
        System.out.println(currentUser.myCalendar.projectedDailySavings);
        System.out.println(currentUser);
        System.out.println((double)(Math.round(3.567 * 100))/100);
        launch(FinancialCalendarApp.class, args);
        sendEmail();
    }
    /**
     * Method for setting up a Calendar
     * based on the information from the
     * data file.       
     */
     public static void initializeStuff()
    {
        try
        {
            Scanner test = new Scanner(new File("myData.data"));
            if (test.hasNext() == false)
            {
                currentUser = new User(0,"","",0,0,0,"financeDefault@gmail.com",0,0);
                currentUser.addCalendar(new FinancialCalendar(0,31,12,2999,GoalType.OTHER));
                return;
            }
            fileScanner = new Scanner(new File("myData.data"));
            String s = fileScanner.nextLine();
            
            Scanner scanner2 = new Scanner(s);
            int endBalance = s.indexOf("|");                  //These numbers tell us where to divide the string 
            int endFirstName = s.indexOf("|", endBalance + 1);//read from the file
            int endLastName = s.indexOf("|", endFirstName + 1);
            int endBirthDate = s.indexOf("|", endLastName + 1);
            int endBirthMonth = s.indexOf("|", endBirthDate + 1);
            int endBirthYear = s.indexOf("|", endBirthMonth + 1);
            int endGoal = s.indexOf("|", endBirthYear + 1);
            int endGoalDate = s.indexOf("|", endGoal + 1);
            int endGoalMonth = s.indexOf("|", endGoalDate + 1);
            int endGoalYear = s.indexOf("|", endGoalMonth + 1);
            int endGoalType = s.indexOf("|", endGoalYear + 1);
            int endEmailAddress = s.indexOf("|", endGoalType + 1);
            int endProjMonthIncome = s.indexOf("|", endEmailAddress + 1);
            int endProjDaySpend = s.indexOf("|", endProjMonthIncome + 1);
            int endAmSavDay = s.indexOf("|", endProjDaySpend + 1);
            int endAmSavWeek = s.indexOf("|", endAmSavDay + 1);
            int endAmSavMonth = s.indexOf("|", endAmSavWeek + 1);
            int endAmSavLastMonth = s.indexOf("|", endAmSavMonth + 1);
            int endAmSav2Month = s.indexOf("|", endAmSavLastMonth + 1);
            int endPrevMonth = s.length();
            currentUser = new User(Double.parseDouble(s.substring(0, endBalance)), 
                    s.substring(endBalance + 1, endFirstName), 
                    s.substring(endFirstName + 1, endLastName), 
                    Integer.parseInt(s.substring(endBirthDate + 1, endBirthMonth)), 
                    Integer.parseInt(s.substring(endLastName + 1, endBirthDate)), 
                    Integer.parseInt(s.substring(endBirthMonth + 1, endBirthYear)), 
                    s.substring(endGoalType + 1, endEmailAddress), 
                    Double.parseDouble(s.substring(endEmailAddress + 1, endProjMonthIncome)), 
                    Double.parseDouble(s.substring(endProjMonthIncome + 1, endProjDaySpend)));
            GoalType gT;
            switch (Integer.parseInt(s.substring(endGoalYear + 1, endGoalType)))
            {
                case 0: gT = GoalType.OTHER;
                    break;
                case 1: gT = GoalType.HOUSE;
                    break;
                case 2: gT = GoalType.BOAT;
                    break;
                case 3: gT = GoalType.VACATION;
                    break;
                case 4: gT = GoalType.LOAN;
                    break;
                case 5: gT = GoalType.FOOD;
                    break;
                case 6: gT = GoalType.NEW_CAR;
                    break;
                case 7: gT = GoalType.SAVINGS;
                    break;
                default: gT = GoalType.OTHER;
            }
            currentUser.addCalendar(new FinancialCalendar(Double.parseDouble(s.substring(endBirthYear + 1, endGoal)),  Integer.parseInt(s.substring(endGoal + 1, endGoalDate)), Integer.parseInt(s.substring(endGoalDate + 1, endGoalMonth)), Integer.parseInt(s.substring(endGoalMonth + 1, endGoalYear)), gT));
            currentUser.amountSavedToday = Double.parseDouble(s.substring(endProjDaySpend + 1, endAmSavDay));
            currentUser.amountSavedThisWeek = Double.parseDouble(s.substring(endAmSavDay + 1, endAmSavWeek));
            currentUser.amountSavedThisMonth = Double.parseDouble(s.substring(endAmSavWeek + 1, endAmSavMonth));
            currentUser.amountSavedLastMonth = Double.parseDouble(s.substring(endAmSavMonth + 1, endAmSavLastMonth));
            currentUser.amountSaved2MonthsAgo = Double.parseDouble(s.substring(endAmSavLastMonth + 1, endAmSav2Month));
            currentUser.prevMonth = Integer.parseInt(s.substring(endAmSav2Month + 1, endPrevMonth));
        }
        catch(FileNotFoundException ex){System.out.println(ex);}
        catch(NullPointerException ex)
        {
            currentUser = new User(0,"","",0,0,0,"financeDefault@gmail.com",0,0);
        }
    }
     /**
      * Saves the current data variables
      * to the data file. Performed upon
      * program exit.
      */
    public static void writeToFile()
    {
        try
        {
            FileOutputStream eraser = new FileOutputStream("myData.data", false);
            eraser.write((new String()).getBytes());
            eraser.close();
            fileWriter = new PrintWriter("myData.data");
            fileWriter.println(currentUser.toString());
            fileWriter.close();
        }
        catch (IOException e){}
    }
    
    /**
     * Displays user information
     * (mainly for testing purposes).
     */    
    public static void print()
    {
        System.out.println(currentUser.toString());
    }
    
    /**
     * Sends an e-mail to the user
     * containing a detailed
     * financial report.
     */
    public static void sendEmail() 
    {
        final String username = "financial.bro.email@gmail.com";
        final String password = "hunter2hunter2";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try 
        {
            Calendar cal = Calendar.getInstance();
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("financial.bro.email@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(currentUser.emailAddress));
            message.setSubject("Weekly Financial Update - GreenNinja");
            message.setText("Happy " + (cal.get(Calendar.YEAR) - currentUser.birthYear) + "th birthday from your Financial Buddy, " + currentUser.firstName);

            Transport.send(message);

            System.out.println("Done");
        } 
        catch (MessagingException e)
        {
            throw new RuntimeException(e);
        }
    }
    
}
